﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace Solidi
{
	public class DependencyTypeComposer : IDependencyComposer
	{
		private DependencyType _type;

		public DependencyTypeComposer(Type type)
		{
			//PERF: cache DependencyType
			_type = new DependencyType(type);
		}

		public object Compose(IDependencyContainer container)
		{
			foreach (DependencyConstructor constructor in _type.Constructors)
			{
				DependencyConstructorParameter[] parameters = constructor.Parameters;

				if (parameters.Length > 0)
				{
					object[] values = ResolveParameters(container, parameters);

					if (values != null)
					{
						return constructor.Create(values);
					}
				}
				else
				{
					return constructor.Create(null);
				}
			}

			return null;
		}

		private static object[] ResolveParameters(IDependencyContainer container, DependencyConstructorParameter[] parameters)
		{
			object[] values = new object[parameters.Length];

			for (int i = 0; i < parameters.Length; i++)
			{
				DependencyConstructorParameter parameter = parameters[i];

				object o = container.Resolve(parameter.Key);

				if (o != null)
				{
					values[i] = o;
				}
				else
				{
					return null;
				}
			}

			return values;
		}
	}
}
